home *** CD-ROM | disk | FTP | other *** search
/ Risc World 5 / Risc World 5.iso / SOFTWARE / Issue5 / PD / DIRSYNC / LegalStuff / gnudiff / diff3.c < prev    next >
C/C++ Source or Header  |  2004-12-19  |  53KB  |  1,863 lines

  1. /* diff3 - compare three files line by line
  2.  
  3.    Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1998, 2001,
  4.    2002 Free Software Foundation, Inc.
  5.  
  6.    This program is free software; you can redistribute it and/or modify
  7.    it under the terms of the GNU General Public License as published by
  8.    the Free Software Foundation; either version 2, or (at your option)
  9.    any later version.
  10.  
  11.    This program is distributed in the hope that it will be useful,
  12.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  14.    See the GNU General Public License for more details.
  15.  
  16.    You should have received a copy of the GNU General Public License
  17.    along with this program; see the file COPYING.
  18.    If not, write to the Free Software Foundation,
  19.    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  20.  
  21. #include "system.h"
  22.  
  23. static char const copyright_string[] =
  24.   "Copyright (C) 2002 Free Software Foundation, Inc.";
  25.  
  26. static char const authorship_msgid[] = N_("Written by Randy Smith.");
  27.  
  28. #include <c-stack.h>
  29. #include <cmpbuf.h>
  30. #include <error.h>
  31. #include <exitfail.h>
  32. #include <freesoft.h>
  33. #include <getopt.h>
  34. #include <inttostr.h>
  35. #include <quotesys.h>
  36. #include <stdio.h>
  37. #include <xalloc.h>
  38.  
  39. #ifdef __riscos
  40. # include <kernel.h>
  41. # include "ro_uname.h"
  42. #endif
  43.  
  44. extern char const version_string[];
  45.  
  46. /*
  47.  * Internal data structures and macros for the diff3 program; includes
  48.  * data structures for both diff3 diffs and normal diffs.
  49.  */
  50.  
  51. /* Different files within a three way diff.  */
  52. #define    FILE0    0
  53. #define    FILE1    1
  54. #define    FILE2    2
  55.  
  56. /*
  57.  * A three way diff is built from two two-way diffs; the file which
  58.  * the two two-way diffs share is:
  59.  */
  60. #define    FILEC    FILE2
  61.  
  62. /*
  63.  * Different files within a two way diff.
  64.  * FC is the common file, FO the other file.
  65.  */
  66. #define FO 0
  67. #define FC 1
  68.  
  69. /* The ranges are indexed by */
  70. #define    RANGE_START    0
  71. #define    RANGE_END    1
  72.  
  73. enum diff_type {
  74.   ERROR,            /* Should not be used */
  75.   ADD,                /* Two way diff add */
  76.   CHANGE,            /* Two way diff change */
  77.   DELETE,            /* Two way diff delete */
  78.   DIFF_ALL,            /* All three are different */
  79.   DIFF_1ST,            /* Only the first is different */
  80.   DIFF_2ND,            /* Only the second */
  81.   DIFF_3RD            /* Only the third */
  82. };
  83.  
  84. /* Two way diff */
  85. struct diff_block {
  86.   lin ranges[2][2];        /* Ranges are inclusive */
  87.   char **lines[2];        /* The actual lines (may contain nulls) */
  88.   size_t *lengths[2];        /* Line lengths (including newlines, if any) */
  89.   struct diff_block *next;
  90. };
  91.  
  92. /* Three way diff */
  93.  
  94. struct diff3_block {
  95.   enum diff_type correspond;    /* Type of diff */
  96.   lin ranges[3][2];        /* Ranges are inclusive */
  97.   char **lines[3];        /* The actual lines (may contain nulls) */
  98.   size_t *lengths[3];        /* Line lengths (including newlines, if any) */
  99.   struct diff3_block *next;
  100. };
  101.  
  102. /*
  103.  * Access the ranges on a diff block.
  104.  */
  105. #define    D_LOWLINE(diff, filenum)    \
  106.   ((diff)->ranges[filenum][RANGE_START])
  107. #define    D_HIGHLINE(diff, filenum)    \
  108.   ((diff)->ranges[filenum][RANGE_END])
  109. #define    D_NUMLINES(diff, filenum)    \
  110.   (D_HIGHLINE (diff, filenum) - D_LOWLINE (diff, filenum) + 1)
  111.  
  112. /*
  113.  * Access the line numbers in a file in a diff by relative line
  114.  * numbers (i.e. line number within the diff itself).  Note that these
  115.  * are lvalues and can be used for assignment.
  116.  */
  117. #define    D_RELNUM(diff, filenum, linenum)    \
  118.   ((diff)->lines[filenum][linenum])
  119. #define    D_RELLEN(diff, filenum, linenum)    \
  120.   ((diff)->lengths[filenum][linenum])
  121.  
  122. /*
  123.  * And get at them directly, when that should be necessary.
  124.  */
  125. #define    D_LINEARRAY(diff, filenum)    \
  126.   ((diff)->lines[filenum])
  127. #define    D_LENARRAY(diff, filenum)    \
  128.   ((diff)->lengths[filenum])
  129.  
  130. /*
  131.  * Next block.
  132.  */
  133. #define    D_NEXT(diff)    ((diff)->next)
  134.  
  135. /*
  136.  * Access the type of a diff3 block.
  137.  */
  138. #define    D3_TYPE(diff)    ((diff)->correspond)
  139.  
  140. /*
  141.  * Line mappings based on diffs.  The first maps off the top of the
  142.  * diff, the second off of the bottom.
  143.  */
  144. #define    D_HIGH_MAPLINE(diff, fromfile, tofile, linenum)    \
  145.   ((linenum)                        \
  146.    - D_HIGHLINE ((diff), (fromfile))            \
  147.    + D_HIGHLINE ((diff), (tofile)))
  148.  
  149. #define    D_LOW_MAPLINE(diff, fromfile, tofile, linenum)    \
  150.   ((linenum)                        \
  151.    - D_LOWLINE ((diff), (fromfile))            \
  152.    + D_LOWLINE ((diff), (tofile)))
  153.  
  154. /* Options variables for flags set on command line.  */
  155.  
  156. /* If nonzero, treat all files as text files, never as binary.  */
  157. static bool text;
  158.  
  159. /* If nonzero, write out an ed script instead of the standard diff3 format.  */
  160. static bool edscript;
  161.  
  162. /* If nonzero, in the case of overlapping diffs (type DIFF_ALL),
  163.    preserve the lines which would normally be deleted from
  164.    file 1 with a special flagging mechanism.  */
  165. static bool flagging;
  166.  
  167. /* Use a tab to align output lines (-T).  */
  168. static bool initial_tab;
  169.  
  170. /* If nonzero, do not output information for overlapping diffs.  */
  171. static bool simple_only;
  172.  
  173. /* If nonzero, do not output information for non-overlapping diffs.  */
  174. static bool overlap_only;
  175.  
  176. /* If nonzero, show information for DIFF_2ND diffs.  */
  177. static bool show_2nd;
  178.  
  179. /* If nonzero, include `:wq' at the end of the script
  180.    to write out the file being edited.   */
  181. static bool finalwrite;
  182.  
  183. /* If nonzero, output a merged file.  */
  184. static bool merge;
  185.  
  186. char *program_name;
  187.  
  188. #ifdef __riscos
  189. const char *extension_names;
  190. int append_filetypes;
  191. #endif
  192.  
  193. static char *read_diff (char const *, char const *, char **);
  194. static char *scan_diff_line (char *, char **, size_t *, char *, char);
  195. static enum diff_type process_diff_control (char **, struct diff_block *);
  196. static bool compare_line_list (char * const[], size_t const[], char * const[], size_t const[], lin);
  197. static bool copy_stringlist (char * const[], size_t const[], char *[], size_t[], lin);
  198. static bool output_diff3_edscript (FILE *, struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *);
  199. static bool output_diff3_merge (FILE *, FILE *, struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *);
  200. static struct diff3_block *create_diff3_block (lin, lin, lin, lin, lin, lin);
  201. static struct diff3_block *make_3way_diff (struct diff_block *, struct diff_block *);
  202. static struct diff3_block *reverse_diff3_blocklist (struct diff3_block *);
  203. static struct diff3_block *using_to_diff3_block (struct diff_block *[2], struct diff_block *[2], int, int, struct diff3_block const *);
  204. static struct diff_block *process_diff (char const *, char const *, struct diff_block **);
  205. static void check_stdout (void);
  206. static void fatal (char const *) __attribute__((noreturn));
  207. static void output_diff3 (FILE *, struct diff3_block *, int const[3], int const[3]);
  208. static void perror_with_exit (char const *) __attribute__((noreturn));
  209. static void try_help (char const *, char const *) __attribute__((noreturn));
  210. static void usage (void);
  211.  
  212. static char const *diff_program = DEFAULT_DIFF_PROGRAM;
  213.  
  214. /* Values for long options that do not have single-letter equivalents.  */
  215. enum
  216. {
  217.   DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
  218.   HELP_OPTION
  219. };
  220.  
  221. static struct option const longopts[] =
  222. {
  223.   {"text", 0, 0, 'a'},
  224.   {"show-all", 0, 0, 'A'},
  225.   {"ed", 0, 0, 'e'},
  226.   {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
  227.   {"show-overlap", 0, 0, 'E'},
  228.   {"label", 1, 0, 'L'},
  229.   {"merge", 0, 0, 'm'},
  230.   {"initial-tab", 0, 0, 'T'},
  231.   {"overlap-only", 0, 0, 'x'},
  232.   {"easy-only", 0, 0, '3'},
  233. #ifdef __riscos
  234. # define RO_EXTRA_OPTS "/::&"
  235.   {"unix-filenames", 2, 0, '/'},
  236.   {"append-filetypes", 0, 0, '&'},
  237. #else
  238. # define RO_EXTRA_OPTS
  239. #endif
  240.   {"version", 0, 0, 'v'},
  241.   {"help", 0, 0, HELP_OPTION},
  242.   {0, 0, 0, 0}
  243. };
  244.  
  245. /*
  246.  * Main program.  Calls diff twice on two pairs of input files,
  247.  * combines the two diffs, and outputs them.
  248.  */
  249. int
  250. main (int argc, char **argv)
  251. {
  252.   int c, i;
  253.   int common;
  254.   int mapping[3];
  255.   int rev_mapping[3];
  256.   int incompat = 0;
  257.   bool conflicts_found;
  258.   struct diff_block *thread0, *thread1, *last_block;
  259.   struct diff3_block *diff3;
  260.   int tag_count = 0;
  261.   char *tag_strings[3];
  262.   char *commonname;
  263.   char **file;
  264.   struct stat statb;
  265.  
  266.   exit_failure = 2;
  267.   initialize_main (&argc, &argv);
  268.   program_name = argv[0];
  269.   setlocale (LC_ALL, "");
  270.   bindtextdomain (PACKAGE, LOCALEDIR);
  271.   textdomain (PACKAGE);
  272.   c_stack_action (c_stack_die);
  273.  
  274.   while ((c = getopt_long (argc, argv, "aeimvx3AEL:TX" RO_EXTRA_OPTS, longopts, 0)) != -1)
  275.     {
  276.       switch (c)
  277.     {
  278.     case 'a':
  279.       text = 1;
  280.       break;
  281.     case 'A':
  282.       show_2nd = 1;
  283.       flagging = 1;
  284.       incompat++;
  285.       break;
  286.     case 'x':
  287.       overlap_only = 1;
  288.       incompat++;
  289.       break;
  290.     case '3':
  291.       simple_only = 1;
  292.       incompat++;
  293.       break;
  294.     case 'i':
  295.       finalwrite = 1;
  296.       break;
  297.     case 'm':
  298.       merge = 1;
  299.       break;
  300.     case 'X':
  301.       overlap_only = 1;
  302.       /* Fall through.  */
  303.     case 'E':
  304.       flagging = 1;
  305.       /* Fall through.  */
  306.     case 'e':
  307.       incompat++;
  308.       break;
  309.     case 'T':
  310.       initial_tab = 1;
  311.       break;
  312.     case 'v':
  313.       printf ("diff3 %s\n%s\n\n%s\n\n%s\n",
  314.           version_string, copyright_string,
  315.           _(free_software_msgid), _(authorship_msgid));
  316.       check_stdout ();
  317.       return EXIT_SUCCESS;
  318.     case DIFF_PROGRAM_OPTION:
  319.       diff_program = optarg;
  320.       break;
  321.     case HELP_OPTION:
  322.       usage ();
  323.       check_stdout ();
  324.       return EXIT_SUCCESS;
  325.     case 'L':
  326.       /* Handle up to three -L options.  */
  327.       if (tag_count < 3)
  328.         {
  329.           tag_strings[tag_count++] = optarg;
  330.           break;
  331.         }
  332.       try_help ("too many file label options", 0);
  333. #ifdef __riscos
  334.     case '/':
  335.       extension_names = optarg ? optarg : "";
  336.       break;
  337.     case '&':
  338.       append_filetypes = 1;
  339.       break;
  340. #endif
  341.     default:
  342.       try_help (0, 0);
  343.     }
  344.     }
  345.  
  346.   edscript = incompat & ~merge;  /* -AeExX3 without -m implies ed script.  */
  347.   show_2nd |= ~incompat & merge;  /* -m without -AeExX3 implies -A.  */
  348.   flagging |= ~incompat & merge;
  349.  
  350.   if (incompat > 1  /* Ensure at most one of -AeExX3.  */
  351.       || finalwrite & merge /* -i -m would rewrite input file.  */
  352.       || (tag_count && ! flagging)) /* -L requires one of -AEX.  */
  353.     try_help ("incompatible options", 0);
  354.  
  355.   if (argc - optind != 3)
  356.     {
  357.       if (argc - optind < 3)
  358.     try_help ("missing operand after `%s'", argv[argc - 1]);
  359.       else
  360.     try_help ("extra operand `%s'", argv[optind + 3]);
  361.     }
  362.  
  363.   file = &argv[optind];
  364.  
  365.   for (i = tag_count; i < 3; i++)
  366.     tag_strings[i] = file[i];
  367.  
  368.   /* Always compare file1 to file2, even if file2 is "-".
  369.      This is needed for -mAeExX3.  Using the file0 as
  370.      the common file would produce wrong results, because if the
  371.      file0-file1 diffs didn't line up with the file0-file2 diffs
  372.      (which is entirely possible since we don't use diff's -n option),
  373.      diff3 might report phantom changes from file1 to file2.
  374.  
  375.      Also, try to compare file0 to file1, because this is where
  376.      changes are expected to come from.  Diffing between these pairs
  377.      of files is more likely to avoid phantom changes from file0 to file1.
  378.  
  379.      Historically, the default common file was file2, so some older
  380.      applications (e.g. Emacs ediff) used file2 as the ancestor.  So,
  381.      for compatibility, if this is a 3-way diff (not a merge or
  382.      edscript), prefer file2 as the common file.  */
  383.  
  384.   common = 2 - (edscript | merge);
  385.  
  386.   if (strcmp (file[common], "-") == 0)
  387.     {
  388.       /* Sigh.  We've got standard input as the common file.  We can't
  389.      call diff twice on stdin.  Use the other arg as the common
  390.      file instead.  */
  391.       common = 3 - common;
  392.       if (strcmp (file[0], "-") == 0 || strcmp (file[common], "-") == 0)
  393.     fatal ("`-' specified for more than one input file");
  394.     }
  395.  
  396.   mapping[0] = 0;
  397.   mapping[1] = 3 - common;
  398.   mapping[2] = common;
  399.  
  400.   for (i = 0; i < 3; i++)
  401.     rev_mapping[mapping[i]] = i;
  402.  
  403.   for (i = 0; i < 3; i++)
  404.     if (strcmp (file[i], "-") != 0)
  405.       {
  406.     if (stat (file[i], &statb) < 0)
  407.       perror_with_exit (file[i]);
  408.     else if (S_ISDIR (statb.st_mode))
  409.       error (EXIT_TROUBLE, EISDIR, "%s", file[i]);
  410.       }
  411.  
  412. #ifdef SIGCHLD
  413.   /* System V fork+wait does not work if SIGCHLD is ignored.  */
  414.   signal (SIGCHLD, SIG_DFL);
  415. #endif
  416.  
  417.   commonname = file[rev_mapping[FILEC]];
  418.   thread1 = process_diff (file[rev_mapping[FILE1]], commonname, &last_block);
  419.   thread0 = process_diff (file[rev_mapping[FILE0]], commonname, &last_block);
  420.   diff3 = make_3way_diff (thread0, thread1);
  421.   if (edscript)
  422.     conflicts_found
  423.       = output_diff3_edscript (stdout, diff3, mapping, rev_mapping,
  424.                    tag_strings[0], tag_strings[1], tag_strings[2]);
  425.   else if (merge)
  426.     {
  427.       if (! freopen (file[rev_mapping[FILE0]], "r", stdin))
  428.     perror_with_exit (file[rev_mapping[FILE0]]);
  429.       conflicts_found
  430.     = output_diff3_merge (stdin, stdout, diff3, mapping, rev_mapping,
  431.                   tag_strings[0], tag_strings[1], tag_strings[2]);
  432.       if (ferror (stdin))
  433.     fatal ("read failed");
  434.     }
  435.   else
  436.     {
  437.       output_diff3 (stdout, diff3, mapping, rev_mapping);
  438.       conflicts_found = 0;
  439.     }
  440.  
  441.   check_stdout ();
  442.   exit (conflicts_found);
  443.   return conflicts_found;
  444. }
  445.  
  446. static void
  447. try_help (char const *reason_msgid, char const *operand)
  448. {
  449.   if (reason_msgid)
  450.     error (0, 0, _(reason_msgid), operand);
  451.   error (EXIT_TROUBLE, 0,
  452.      _("Try `%s --help' for more information."), program_name);
  453.   abort ();
  454. }
  455.  
  456. static void
  457. check_stdout (void)
  458. {
  459.   if (ferror (stdout))
  460.     fatal ("write failed");
  461.   else if (fclose (stdout) != 0)
  462.     perror_with_exit (_("standard output"));
  463. }
  464.  
  465. static char const * const option_help_msgid[] = {
  466.   N_("-e  --ed  Output unmerged changes from OLDFILE to YOURFILE into MYFILE."),
  467.   N_("-E  --show-overlap  Output unmerged changes, bracketing conflicts."),
  468.   N_("-A  --show-all  Output all changes, bracketing conflicts."),
  469.   N_("-x  --overlap-only  Output overlapping changes."),
  470.   N_("-X  Output overlapping changes, bracketing them."),
  471.   N_("-3  --easy-only  Output unmerged nonoverlapping changes."),
  472.   "",
  473.   N_("-m  --merge  Output merged file instead of ed script (default -A)."),
  474.   N_("-L LABEL  --label=LABEL  Use LABEL instead of file name."),
  475.   N_("-i  Append `w' and `q' commands to ed scripts."),
  476.   N_("-a  --text  Treat all files as text."),
  477.   N_("-T  --initial-tab  Make tabs line up by prepending a tab."),
  478.   N_("--diff-program=PROGRAM  Use PROGRAM to compare files."),
  479.   "",
  480. #ifdef __riscos
  481.   "-/ [EXT]  --unix-filenames[=EXT]  Output Unix-style filenames with optional\n\
  482.            EXTension swapping. '-/ c:h:o' causes, eg. 'foo.c.bar' -> 'foo/bar.c'",
  483.   "-&        --append-filetypes      Append filetypes in Acorn NFS format.",
  484.   "",
  485. #endif
  486.   N_("-v  --version  Output version info."),
  487.   N_("--help  Output this help."),
  488.   0
  489. };
  490.  
  491. static void
  492. usage (void)
  493. {
  494.   char const * const *p;
  495.  
  496.   printf (_("Usage: %s [OPTION]... MYFILE OLDFILE YOURFILE\n"),
  497.       program_name);
  498.   printf ("%s\n\n", _("Compare three files line by line."));
  499.   for (p = option_help_msgid;  *p;  p++)
  500.     if (**p)
  501.       printf ("  %s\n", _(*p));
  502.     else
  503.       putchar ('\n');
  504.   printf ("\n%s\n\n%s\n",
  505.       _("If a FILE is `-', read standard input."),
  506.       _("Report bugs to <bug-gnu-utils@gnu.org>."));
  507. }
  508.  
  509. /*
  510.  * Routines that combine the two diffs together into one.  The
  511.  * algorithm used follows:
  512.  *
  513.  *   File2 is shared in common between the two diffs.
  514.  *   Diff02 is the diff between 0 and 2.
  515.  *   Diff12 is the diff between 1 and 2.
  516.  *
  517.  *    1) Find the range for the first block in File2.
  518.  *        a) Take the lowest of the two ranges (in File2) in the two
  519.  *           current blocks (one from each diff) as being the low
  520.  *           water mark.  Assign the upper end of this block as
  521.  *           being the high water mark and move the current block up
  522.  *           one.  Mark the block just moved over as to be used.
  523.  *        b) Check the next block in the diff that the high water
  524.  *           mark is *not* from.
  525.  *
  526.  *           *If* the high water mark is above
  527.  *           the low end of the range in that block,
  528.  *
  529.  *           mark that block as to be used and move the current
  530.  *           block up.  Set the high water mark to the max of
  531.  *           the high end of this block and the current.  Repeat b.
  532.  *
  533.  *     2) Find the corresponding ranges in File0 (from the blocks
  534.  *        in diff02; line per line outside of diffs) and in File1.
  535.  *        Create a diff3_block, reserving space as indicated by the ranges.
  536.  *
  537.  *     3) Copy all of the pointers for file2 in.  At least for now,
  538.  *        do memcmp's between corresponding strings in the two diffs.
  539.  *
  540.  *     4) Copy all of the pointers for file0 and 1 in.  Get what you
  541.  *        need from file2 (when there isn't a diff block, it's
  542.  *        identical to file2 within the range between diff blocks).
  543.  *
  544.  *     5) If the diff blocks you used came from only one of the two
  545.  *        strings of diffs, then that file (i.e. the one other than
  546.  *        the common file in that diff) is the odd person out.  If you used
  547.  *        diff blocks from both sets, check to see if files 0 and 1 match:
  548.  *
  549.  *        Same number of lines?  If so, do a set of memcmp's (if a
  550.  *        memcmp matches; copy the pointer over; it'll be easier later
  551.  *        if you have to do any compares).  If they match, 0 & 1 are
  552.  *        the same.  If not, all three different.
  553.  *
  554.  *   Then you do it again, until you run out of blocks.
  555.  *
  556.  */
  557.  
  558. /*
  559.  * This routine makes a three way diff (chain of diff3_block's) from two
  560.  * two way diffs (chains of diff_block's).  It is assumed that each of
  561.  * the two diffs passed are onto the same file (i.e. that each of the
  562.  * diffs were made "to" the same file).  The three way diff pointer
  563.  * returned will have numbering FILE0--the other file in diff02,
  564.  * FILE1--the other file in diff12, and FILEC--the common file.
  565.  */
  566. static struct diff3_block *
  567. make_3way_diff (struct diff_block *thread0, struct diff_block *thread1)
  568. {
  569. /*
  570.  * This routine works on the two diffs passed to it as threads.
  571.  * Thread number 0 is diff02, thread number 1 is diff12.  The USING
  572.  * array is set to the base of the list of blocks to be used to
  573.  * construct each block of the three way diff; if no blocks from a
  574.  * particular thread are to be used, that element of the using array
  575.  * is set to 0.  The elements LAST_USING array are set to the last
  576.  * elements on each of the using lists.
  577.  *
  578.  * The HIGH_WATER_MARK is set to the highest line number in the common file
  579.  * described in any of the diffs in either of the USING lists.  The
  580.  * HIGH_WATER_THREAD names the thread.  Similarly the BASE_WATER_MARK
  581.  * and BASE_WATER_THREAD describe the lowest line number in the common file
  582.  * described in any of the diffs in either of the USING lists.  The
  583.  * HIGH_WATER_DIFF is the diff from which the HIGH_WATER_MARK was
  584.  * taken.
  585.  *
  586.  * The HIGH_WATER_DIFF should always be equal to LAST_USING
  587.  * [HIGH_WATER_THREAD].  The OTHER_DIFF is the next diff to check for
  588.  * higher water, and should always be equal to
  589.  * CURRENT[HIGH_WATER_THREAD ^ 0x1].  The OTHER_THREAD is the thread
  590.  * in which the OTHER_DIFF is, and hence should always be equal to
  591.  * HIGH_WATER_THREAD ^ 0x1.
  592.  *
  593.  * The variable LAST_DIFF is kept set to the last diff block produced
  594.  * by this routine, for line correspondence purposes between that diff
  595.  * and the one currently being worked on.  It is initialized to
  596.  * ZERO_DIFF before any blocks have been created.
  597.  */
  598.  
  599.   struct diff_block *using[2];
  600.   struct diff_block *last_using[2];
  601.   struct diff_block *current[2];
  602.  
  603.   lin high_water_mark;
  604.  
  605.   int high_water_thread;
  606.   int base_water_thread;
  607.   int other_thread;
  608.  
  609.   struct diff_block *high_water_diff;
  610.   struct diff_block *other_diff;
  611.  
  612.   struct diff3_block *result;
  613.   struct diff3_block *tmpblock;
  614.   struct diff3_block **result_end;
  615.  
  616.   struct diff3_block const *last_diff3;
  617.  
  618.   static struct diff3_block const zero_diff3;
  619.  
  620.   /* Initialization */
  621.   result = 0;
  622.   result_end = &result;
  623.   current[0] = thread0; current[1] = thread1;
  624.   last_diff3 = &zero_diff3;
  625.  
  626.   /* Sniff up the threads until we reach the end */
  627.  
  628.   while (current[0] || current[1])
  629.     {
  630.       using[0] = using[1] = last_using[0] = last_using[1] = 0;
  631.  
  632.       /* Setup low and high water threads, diffs, and marks.  */
  633.       if (!current[0])
  634.     base_water_thread = 1;
  635.       else if (!current[1])
  636.     base_water_thread = 0;
  637.       else
  638.     base_water_thread =
  639.       (D_LOWLINE (current[0], FC) > D_LOWLINE (current[1], FC));
  640.  
  641.       high_water_thread = base_water_thread;
  642.  
  643.       high_water_diff = current[high_water_thread];
  644.  
  645.       high_water_mark = D_HIGHLINE (high_water_diff, FC);
  646.  
  647.       /* Make the diff you just got info from into the using class */
  648.       using[high_water_thread]
  649.     = last_using[high_water_thread]
  650.     = high_water_diff;
  651.       current[high_water_thread] = high_water_diff->next;
  652.       last_using[high_water_thread]->next = 0;
  653.  
  654.       /* And mark the other diff */
  655.       other_thread = high_water_thread ^ 0x1;
  656.       other_diff = current[other_thread];
  657.  
  658.       /* Shuffle up the ladder, checking the other diff to see if it
  659.      needs to be incorporated.  */
  660.       while (other_diff
  661.          && D_LOWLINE (other_diff, FC) <= high_water_mark + 1)
  662.     {
  663.  
  664.       /* Incorporate this diff into the using list.  Note that
  665.          this doesn't take it off the current list */
  666.       if (using[other_thread])
  667.         last_using[other_thread]->next = other_diff;
  668.       else
  669.         using[other_thread] = other_diff;
  670.       last_using[other_thread] = other_diff;
  671.  
  672.       /* Take it off the current list.  Note that this following
  673.          code assumes that other_diff enters it equal to
  674.          current[high_water_thread ^ 0x1] */
  675.       current[other_thread] = current[other_thread]->next;
  676.       other_diff->next = 0;
  677.  
  678.       /* Set the high_water stuff
  679.          If this comparison is equal, then this is the last pass
  680.          through this loop; since diff blocks within a given
  681.          thread cannot overlap, the high_water_mark will be
  682.          *below* the range_start of either of the next diffs.  */
  683.  
  684.       if (high_water_mark < D_HIGHLINE (other_diff, FC))
  685.         {
  686.           high_water_thread ^= 1;
  687.           high_water_diff = other_diff;
  688.           high_water_mark = D_HIGHLINE (other_diff, FC);
  689.         }
  690.  
  691.       /* Set the other diff */
  692.       other_thread = high_water_thread ^ 0x1;
  693.       other_diff = current[other_thread];
  694.     }
  695.  
  696.       /* The using lists contain a list of all of the blocks to be
  697.      included in this diff3_block.  Create it.  */
  698.  
  699.       tmpblock = using_to_diff3_block (using, last_using,
  700.                        base_water_thread, high_water_thread,
  701.                        last_diff3);
  702.  
  703.       if (!tmpblock)
  704.     fatal ("internal error: screwup in format of diff blocks");
  705.  
  706.       /* Put it on the list.  */
  707.       *result_end = tmpblock;
  708.       result_end = &tmpblock->next;
  709.  
  710.       /* Set up corresponding lines correctly.  */
  711.       last_diff3 = tmpblock;
  712.     }
  713.   return result;
  714. }
  715.  
  716. /*
  717.  * using_to_diff3_block:
  718.  *   This routine takes two lists of blocks (from two separate diff
  719.  * threads) and puts them together into one diff3 block.
  720.  * It then returns a pointer to this diff3 block or 0 for failure.
  721.  *
  722.  * All arguments besides using are for the convenience of the routine;
  723.  * they could be derived from the using array.
  724.  * LAST_USING is a pair of pointers to the last blocks in the using
  725.  * structure.
  726.  * LOW_THREAD and HIGH_THREAD tell which threads contain the lowest
  727.  * and highest line numbers for File0.
  728.  * last_diff3 contains the last diff produced in the calling routine.
  729.  * This is used for lines mappings which would still be identical to
  730.  * the state that diff ended in.
  731.  *
  732.  * A distinction should be made in this routine between the two diffs
  733.  * that are part of a normal two diff block, and the three diffs that
  734.  * are part of a diff3_block.
  735.  */
  736. static struct diff3_block *
  737. using_to_diff3_block (struct diff_block *using[2],
  738.               struct diff_block *last_using[2],
  739.               int low_thread, int high_thread,
  740.               struct diff3_block const *last_diff3)
  741. {
  742.   lin low[2], high[2];
  743.   struct diff3_block *result;
  744.   struct diff_block *ptr;
  745.   int d;
  746.   lin i;
  747.  
  748.   /* Find the range in the common file.  */
  749.   lin lowc = D_LOWLINE (using[low_thread], FC);
  750.   lin highc = D_HIGHLINE (last_using[high_thread], FC);
  751.  
  752.   /* Find the ranges in the other files.
  753.      If using[d] is null, that means that the file to which that diff
  754.      refers is equivalent to the common file over this range.  */
  755.  
  756.   for (d = 0; d < 2; d++)
  757.     if (using[d])
  758.       {
  759.     low[d] = D_LOW_MAPLINE (using[d], FC, FO, lowc);
  760.     high[d] = D_HIGH_MAPLINE (last_using[d], FC, FO, highc);
  761.       }
  762.     else
  763.       {
  764.     low[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, lowc);
  765.     high[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, highc);
  766.       }
  767.  
  768.   /* Create a block with the appropriate sizes */
  769.   result = create_diff3_block (low[0], high[0], low[1], high[1], lowc, highc);
  770.  
  771.   /* Copy information for the common file.
  772.      Return with a zero if any of the compares failed.  */
  773.  
  774.   for (d = 0; d < 2; d++)
  775.     for (ptr = using[d]; ptr; ptr = D_NEXT (ptr))
  776.       {
  777.     lin result_offset = D_LOWLINE (ptr, FC) - lowc;
  778.  
  779.     if (!copy_stringlist (D_LINEARRAY (ptr, FC),
  780.                   D_LENARRAY (ptr, FC),
  781.                   D_LINEARRAY (result, FILEC) + result_offset,
  782.                   D_LENARRAY (result, FILEC) + result_offset,
  783.                   D_NUMLINES (ptr, FC)))
  784.       return 0;
  785.       }
  786.  
  787.   /* Copy information for file d.  First deal with anything that might be
  788.      before the first diff.  */
  789.  
  790.   for (d = 0; d < 2; d++)
  791.     {
  792.       struct diff_block *u = using[d];
  793.       lin lo = low[d], hi = high[d];
  794.  
  795.       for (i = 0;
  796.        i + lo < (u ? D_LOWLINE (u, FO) : hi + 1);
  797.        i++)
  798.     {
  799.       D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, i);
  800.       D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, i);
  801.     }
  802.  
  803.       for (ptr = u; ptr; ptr = D_NEXT (ptr))
  804.     {
  805.       lin result_offset = D_LOWLINE (ptr, FO) - lo;
  806.       lin linec;
  807.  
  808.       if (!copy_stringlist (D_LINEARRAY (ptr, FO),
  809.                 D_LENARRAY (ptr, FO),
  810.                 D_LINEARRAY (result, FILE0 + d) + result_offset,
  811.                 D_LENARRAY (result, FILE0 + d) + result_offset,
  812.                 D_NUMLINES (ptr, FO)))
  813.         return 0;
  814.  
  815.       /* Catch the lines between here and the next diff */
  816.       linec = D_HIGHLINE (ptr, FC) + 1 - lowc;
  817.       for (i = D_HIGHLINE (ptr, FO) + 1 - lo;
  818.            i < (D_NEXT (ptr) ? D_LOWLINE (D_NEXT (ptr), FO) : hi + 1) - lo;
  819.            i++)
  820.         {
  821.           D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, linec);
  822.           D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, linec);
  823.           linec++;
  824.         }
  825.     }
  826.     }
  827.  
  828.   /* Set correspond */
  829.   if (!using[0])
  830.     D3_TYPE (result) = DIFF_2ND;
  831.   else if (!using[1])
  832.     D3_TYPE (result) = DIFF_1ST;
  833.   else
  834.     {
  835.       lin nl0 = D_NUMLINES (result, FILE0);
  836.       lin nl1 = D_NUMLINES (result, FILE1);
  837.  
  838.       if (nl0 != nl1
  839.       || !compare_line_list (D_LINEARRAY (result, FILE0),
  840.                  D_LENARRAY (result, FILE0),
  841.                  D_LINEARRAY (result, FILE1),
  842.                  D_LENARRAY (result, FILE1),
  843.                  nl0))
  844.     D3_TYPE (result) = DIFF_ALL;
  845.       else
  846.     D3_TYPE (result) = DIFF_3RD;
  847.     }
  848.  
  849.   return result;
  850. }
  851.  
  852. /*
  853.  * This routine copies pointers from a list of strings to a different list
  854.  * of strings.  If a spot in the second list is already filled, it
  855.  * makes sure that it is filled with the same string; if not it
  856.  * returns 0, the copy incomplete.
  857.  * Upon successful completion of the copy, it returns 1.
  858.  */
  859. static bool
  860. copy_stringlist (char * const fromptrs[], size_t const fromlengths[],
  861.          char *toptrs[], size_t tolengths[],
  862.          lin copynum)
  863. {
  864.   register char * const *f = fromptrs;
  865.   register char **t = toptrs;
  866.   register size_t const *fl = fromlengths;
  867.   register size_t *tl = tolengths;
  868.  
  869.   while (copynum--)
  870.     {
  871.       if (*t)
  872.     { if (*fl != *tl || memcmp (*f, *t, *fl)) return 0; }
  873.       else
  874.     { *t = *f ; *tl = *fl; }
  875.  
  876.       t++; f++; tl++; fl++;
  877.     }
  878.   return 1;
  879. }
  880.  
  881. /*
  882.  * Create a diff3_block, with ranges as specified in the arguments.
  883.  * Allocate the arrays for the various pointers (and zero them) based
  884.  * on the arguments passed.  Return the block as a result.
  885.  */
  886. static struct diff3_block *
  887. create_diff3_block (lin low0, lin high0,
  888.             lin low1, lin high1,
  889.             lin low2, lin high2)
  890. {
  891.   struct diff3_block *result = xmalloc (sizeof *result);
  892.   lin numlines;
  893.  
  894.   D3_TYPE (result) = ERROR;
  895.   D_NEXT (result) = 0;
  896.  
  897.   /* Assign ranges */
  898.   D_LOWLINE (result, FILE0) = low0;
  899.   D_HIGHLINE (result, FILE0) = high0;
  900.   D_LOWLINE (result, FILE1) = low1;
  901.   D_HIGHLINE (result, FILE1) = high1;
  902.   D_LOWLINE (result, FILE2) = low2;
  903.   D_HIGHLINE (result, FILE2) = high2;
  904.  
  905.   /* Allocate and zero space */
  906.   numlines = D_NUMLINES (result, FILE0);
  907.   if (numlines)
  908.     {
  909.       D_LINEARRAY (result, FILE0) = xcalloc (numlines, sizeof (char *));
  910.       D_LENARRAY (result, FILE0) = xcalloc (numlines, sizeof (size_t));
  911.     }
  912.   else
  913.     {
  914.       D_LINEARRAY (result, FILE0) = 0;
  915.       D_LENARRAY (result, FILE0) = 0;
  916.     }
  917.  
  918.   numlines = D_NUMLINES (result, FILE1);
  919.   if (numlines)
  920.     {
  921.       D_LINEARRAY (result, FILE1) = xcalloc (numlines, sizeof (char *));
  922.       D_LENARRAY (result, FILE1) = xcalloc (numlines, sizeof (size_t));
  923.     }
  924.   else
  925.     {
  926.       D_LINEARRAY (result, FILE1) = 0;
  927.       D_LENARRAY (result, FILE1) = 0;
  928.     }
  929.  
  930.   numlines = D_NUMLINES (result, FILE2);
  931.   if (numlines)
  932.     {
  933.       D_LINEARRAY (result, FILE2) = xcalloc (numlines, sizeof (char *));
  934.       D_LENARRAY (result, FILE2) = xcalloc (numlines, sizeof (size_t));
  935.     }
  936.   else
  937.     {
  938.       D_LINEARRAY (result, FILE2) = 0;
  939.       D_LENARRAY (result, FILE2) = 0;
  940.     }
  941.  
  942.   /* Return */
  943.   return result;
  944. }
  945.  
  946. /*
  947.  * Compare two lists of lines of text.
  948.  * Return 1 if they are equivalent, 0 if not.
  949.  */
  950. static bool
  951. compare_line_list (char * const list1[], size_t const lengths1[],
  952.            char * const list2[], size_t const lengths2[],
  953.            lin nl)
  954. {
  955.   char
  956.     * const *l1 = list1,
  957.     * const *l2 = list2;
  958.   size_t const
  959.     *lgths1 = lengths1,
  960.     *lgths2 = lengths2;
  961.  
  962.   while (nl--)
  963.     if (!*l1 || !*l2 || *lgths1 != *lgths2++
  964.     || memcmp (*l1++, *l2++, *lgths1++))
  965.       return 0;
  966.   return 1;
  967. }
  968.  
  969. /*
  970.  * Routines to input and parse two way diffs.
  971.  */
  972.  
  973. static struct diff_block *
  974. process_diff (char const *filea,
  975.           char const *fileb,
  976.           struct diff_block **last_block)
  977. {
  978.   char *diff_contents;
  979.   char *diff_limit;
  980.   char *scan_diff;
  981.   enum diff_type dt;
  982.   lin i;
  983.   struct diff_block *block_list, **block_list_end, *bptr;
  984.   size_t too_many_lines = (PTRDIFF_MAX
  985.                / MIN (sizeof *bptr->lines[1],
  986.                   sizeof *bptr->lengths[1]));
  987.  
  988.   diff_limit = read_diff (filea, fileb, &diff_contents);
  989.   scan_diff = diff_contents;
  990.   block_list_end = &block_list;
  991.   bptr = 0; /* Pacify `gcc -W'.  */
  992.  
  993.   while (scan_diff < diff_limit)
  994.     {
  995.       bptr = xmalloc (sizeof *bptr);
  996.       bptr->lines[0] = bptr->lines[1] = 0;
  997.       bptr->lengths[0] = bptr->lengths[1] = 0;
  998.  
  999.       dt = process_diff_control (&scan_diff, bptr);
  1000.       if (dt == ERROR || *scan_diff != '\n')
  1001.     {
  1002.       fprintf (stderr, _("%s: diff failed: "), program_name);
  1003.       do
  1004.         {
  1005.           putc (*scan_diff, stderr);
  1006.         }
  1007.       while (*scan_diff++ != '\n');
  1008.       exit (EXIT_TROUBLE);
  1009.     }
  1010.       scan_diff++;
  1011.  
  1012.       /* Force appropriate ranges to be null, if necessary */
  1013.       switch (dt)
  1014.     {
  1015.     case ADD:
  1016.       bptr->ranges[0][0]++;
  1017.       break;
  1018.     case DELETE:
  1019.       bptr->ranges[1][0]++;
  1020.       break;
  1021.     case CHANGE:
  1022.       break;
  1023.     default:
  1024.       fatal ("internal error: invalid diff type in process_diff");
  1025.       break;
  1026.     }
  1027.  
  1028.       /* Allocate space for the pointers for the lines from filea, and
  1029.      parcel them out among these pointers */
  1030.       if (dt != ADD)
  1031.     {
  1032.       lin numlines = D_NUMLINES (bptr, 0);
  1033.       if (too_many_lines <= numlines)
  1034.         xalloc_die ();
  1035.       bptr->lines[0] = xmalloc (numlines * sizeof *bptr->lines[0]);
  1036.       bptr->lengths[0] = xmalloc (numlines * sizeof *bptr->lengths[0]);
  1037.       for (i = 0; i < numlines; i++)
  1038.         scan_diff = scan_diff_line (scan_diff,
  1039.                     &(bptr->lines[0][i]),
  1040.                     &(bptr->lengths[0][i]),
  1041.                     diff_limit,
  1042.                     '<');
  1043.     }
  1044.  
  1045.       /* Get past the separator for changes */
  1046.       if (dt == CHANGE)
  1047.     {
  1048.       if (strncmp (scan_diff, "---\n", 4))
  1049.         fatal ("invalid diff format; invalid change separator");
  1050.       scan_diff += 4;
  1051.     }
  1052.  
  1053.       /* Allocate space for the pointers for the lines from fileb, and
  1054.      parcel them out among these pointers */
  1055.       if (dt != DELETE)
  1056.     {
  1057.       lin numlines = D_NUMLINES (bptr, 1);
  1058.       if (too_many_lines <= numlines)
  1059.         xalloc_die ();
  1060.       bptr->lines[1] = xmalloc (numlines * sizeof *bptr->lines[1]);
  1061.       bptr->lengths[1] = xmalloc (numlines * sizeof *bptr->lengths[1]);
  1062.       for (i = 0; i < numlines; i++)
  1063.         scan_diff = scan_diff_line (scan_diff,
  1064.                     &(bptr->lines[1][i]),
  1065.                     &(bptr->lengths[1][i]),
  1066.                     diff_limit,
  1067.                     '>');
  1068.     }
  1069.  
  1070.       /* Place this block on the blocklist.  */
  1071.       *block_list_end = bptr;
  1072.       block_list_end = &bptr->next;
  1073.     }
  1074.  
  1075.   *block_list_end = 0;
  1076.   *last_block = bptr;
  1077.   return block_list;
  1078. }
  1079.  
  1080. /*
  1081.  * This routine will parse a normal format diff control string.  It
  1082.  * returns the type of the diff (ERROR if the format is bad).  All of
  1083.  * the other important information is filled into to the structure
  1084.  * pointed to by db, and the string pointer (whose location is passed
  1085.  * to this routine) is updated to point beyond the end of the string
  1086.  * parsed.  Note that only the ranges in the diff_block will be set by
  1087.  * this routine.
  1088.  *
  1089.  * If some specific pair of numbers has been reduced to a single
  1090.  * number, then both corresponding numbers in the diff block are set
  1091.  * to that number.  In general these numbers are interpreted as ranges
  1092.  * inclusive, unless being used by the ADD or DELETE commands.  It is
  1093.  * assumed that these will be special cased in a superior routine.
  1094.  */
  1095.  
  1096. static enum diff_type
  1097. process_diff_control (char **string, struct diff_block *db)
  1098. {
  1099.   char *s = *string;
  1100.   lin holdnum;
  1101.   enum diff_type type;
  1102.  
  1103. /* These macros are defined here because they can use variables
  1104.    defined in this function.  Don't try this at home kids, we're
  1105.    trained professionals!
  1106.  
  1107.    Also note that SKIPWHITE only recognizes tabs and spaces, and
  1108.    that READNUM can only read positive, integral numbers */
  1109.  
  1110. #define    SKIPWHITE(s)    { while (*s == ' ' || *s == '\t') s++; }
  1111. #define    READNUM(s, num)    \
  1112.     { unsigned char c = *s; if (!ISDIGIT (c)) return ERROR; holdnum = 0; \
  1113.       do { holdnum = (c - '0' + holdnum * 10); }    \
  1114.       while (ISDIGIT (c = *++s)); (num) = holdnum; }
  1115.  
  1116.   /* Read first set of digits */
  1117.   SKIPWHITE (s);
  1118.   READNUM (s, db->ranges[0][RANGE_START]);
  1119.  
  1120.   /* Was that the only digit? */
  1121.   SKIPWHITE (s);
  1122.   if (*s == ',')
  1123.     {
  1124.       /* Get the next digit */
  1125.       s++;
  1126.       READNUM (s, db->ranges[0][RANGE_END]);
  1127.     }
  1128.   else
  1129.     db->ranges[0][RANGE_END] = db->ranges[0][RANGE_START];
  1130.  
  1131.   /* Get the letter */
  1132.   SKIPWHITE (s);
  1133.   switch (*s)
  1134.     {
  1135.     case 'a':
  1136.       type = ADD;
  1137.       break;
  1138.     case 'c':
  1139.       type = CHANGE;
  1140.       break;
  1141.     case 'd':
  1142.       type = DELETE;
  1143.       break;
  1144.     default:
  1145.       return ERROR;            /* Bad format */
  1146.     }
  1147.   s++;                /* Past letter */
  1148.  
  1149.   /* Read second set of digits */
  1150.   SKIPWHITE (s);
  1151.   READNUM (s, db->ranges[1][RANGE_START]);
  1152.  
  1153.   /* Was that the only digit? */
  1154.   SKIPWHITE (s);
  1155.   if (*s == ',')
  1156.     {
  1157.       /* Get the next digit */
  1158.       s++;
  1159.       READNUM (s, db->ranges[1][RANGE_END]);
  1160.       SKIPWHITE (s);        /* To move to end */
  1161.     }
  1162.   else
  1163.     db->ranges[1][RANGE_END] = db->ranges[1][RANGE_START];
  1164.  
  1165.   *string = s;
  1166.   return type;
  1167. }
  1168.  
  1169. static char *
  1170. read_diff (char const *filea,
  1171.        char const *fileb,
  1172.        char **output_placement)
  1173. {
  1174.   char *diff_result;
  1175.   size_t current_chunk_size, total;
  1176.   int fd, wstatus;
  1177.   int werrno = 0;
  1178.   struct stat pipestat;
  1179.  
  1180. #if HAVE_WORKING_FORK || HAVE_WORKING_VFORK
  1181.  
  1182.   char const *argv[8];
  1183.   char const **ap;
  1184.   int fds[2];
  1185.   pid_t pid;
  1186.  
  1187.   ap = argv;
  1188.   *ap++ = diff_program;
  1189.   if (text)
  1190.     *ap++ = "-a";
  1191.   *ap++ = "--horizon-lines=100";
  1192.   *ap++ = "--";
  1193.   *ap++ = filea;
  1194.   *ap++ = fileb;
  1195.   *ap = 0;
  1196.  
  1197.   if (pipe (fds) != 0)
  1198.     perror_with_exit ("pipe");
  1199.  
  1200.   pid = vfork ();
  1201.   if (pid == 0)
  1202.     {
  1203.       /* Child */
  1204.       close (fds[0]);
  1205.       if (fds[1] != STDOUT_FILENO)
  1206.     {
  1207.       dup2 (fds[1], STDOUT_FILENO);
  1208.       close (fds[1]);
  1209.     }
  1210.  
  1211.       /* The cast to (char **) is needed for portability to older
  1212.      hosts with a nonstandard prototype for execvp.  */
  1213.       execvp (diff_program, (char **) argv);
  1214.  
  1215.       _exit (errno == ENOEXEC ? 126 : 127);
  1216.     }
  1217.  
  1218.   if (pid == -1)
  1219.     perror_with_exit ("fork");
  1220.  
  1221.   close (fds[1]);        /* Prevent erroneous lack of EOF */
  1222.   fd = fds[0];
  1223.  
  1224. #else
  1225.  
  1226.   FILE *fpipe;
  1227.   char const args[] = " -a --horizon-lines=100 -- ";
  1228.   char *command = xmalloc (quote_system_arg (0, diff_program)
  1229.                + sizeof args - 1
  1230.                + quote_system_arg (0, filea) + 1
  1231.                + quote_system_arg (0, fileb) + 1);
  1232.   char *p = command;
  1233.   p += quote_system_arg (p, diff_program);
  1234.   strcpy (p, args + (text ? 0 : 3));
  1235.   p += strlen (p);
  1236.   p += quote_system_arg (p, filea);
  1237.   *p++ = ' ';
  1238.   p += quote_system_arg (p, fileb);
  1239.   *p = 0;
  1240.   errno = 0;
  1241.   fpipe = popen (command, "r");
  1242.   if (!fpipe)
  1243.     perror_with_exit (command);
  1244.   free (command);
  1245.   fd = fileno (fpipe);
  1246.  
  1247. #endif
  1248.  
  1249.   if (fstat (fd, &pipestat) != 0)
  1250.     perror_with_exit ("fstat");
  1251. #ifdef __riscos
  1252.   current_chunk_size = 8 * 1024;
  1253. #else
  1254.   current_chunk_size = MAX (1, STAT_BLOCKSIZE (pipestat));
  1255. #endif
  1256.   diff_result = xmalloc (current_chunk_size);
  1257.   total = 0;
  1258.  
  1259.   for (;;)
  1260.     {
  1261.       size_t bytes_to_read = current_chunk_size - total;
  1262.       size_t bytes = block_read (fd, diff_result + total, bytes_to_read);
  1263.       total += bytes;
  1264.       if (bytes != bytes_to_read)
  1265.     {
  1266.       if (bytes == SIZE_MAX)
  1267.         perror_with_exit (_("read failed"));
  1268.       break;
  1269.     }
  1270.       if (PTRDIFF_MAX / 2 <= current_chunk_size)
  1271.     xalloc_die ();
  1272.       current_chunk_size *= 2;
  1273.       diff_result = xrealloc (diff_result, current_chunk_size);
  1274.     }
  1275.  
  1276.   if (total != 0 && diff_result[total-1] != '\n')
  1277.     fatal ("invalid diff format; incomplete last line");
  1278.  
  1279.   *output_placement = diff_result;
  1280.  
  1281. #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
  1282.  
  1283.   wstatus = pclose (fpipe);
  1284.   if (wstatus == -1)
  1285.     werrno = errno;
  1286.  
  1287. #else
  1288.  
  1289.   if (close (fd) != 0)
  1290.     perror_with_exit ("close");
  1291.   if (waitpid (pid, &wstatus, 0) < 0)
  1292.     perror_with_exit ("waitpid");
  1293.  
  1294. #endif
  1295.  
  1296.   if (! werrno && WIFEXITED (wstatus))
  1297.     switch (WEXITSTATUS (wstatus))
  1298.       {
  1299.       case 126:
  1300.     error (EXIT_TROUBLE, 0, _("subsidiary program `%s' not executable"),
  1301.            diff_program);
  1302.       case 127:
  1303.     error (EXIT_TROUBLE, 0, _("subsidiary program `%s' not found"),
  1304.            diff_program);
  1305.       }
  1306.   if (werrno || ! (WIFEXITED (wstatus) && WEXITSTATUS (wstatus) < 2))
  1307.     error (EXIT_TROUBLE, werrno, _("subsidiary program `%s' failed"),
  1308.        diff_program);
  1309.  
  1310.   return diff_result + total;
  1311. }
  1312.  
  1313.  
  1314. /*
  1315.  * Scan a regular diff line (consisting of > or <, followed by a
  1316.  * space, followed by text (including nulls) up to a newline.
  1317.  *
  1318.  * This next routine began life as a macro and many parameters in it
  1319.  * are used as call-by-reference values.
  1320.  */
  1321. static char *
  1322. scan_diff_line (char *scan_ptr, char **set_start, size_t *set_length,
  1323.         char *limit, char leadingchar)
  1324. {
  1325.   char *line_ptr;
  1326.  
  1327.   if (!(scan_ptr[0] == leadingchar
  1328.     && scan_ptr[1] == ' '))
  1329.     fatal ("invalid diff format; incorrect leading line chars");
  1330.  
  1331.   *set_start = line_ptr = scan_ptr + 2;
  1332.   while (*line_ptr++ != '\n')
  1333.     continue;
  1334.  
  1335.   /* Include newline if the original line ended in a newline,
  1336.      or if an edit script is being generated.
  1337.      Copy any missing newline message to stderr if an edit script is being
  1338.      generated, because edit scripts cannot handle missing newlines.
  1339.      Return the beginning of the next line.  */
  1340.   *set_length = line_ptr - *set_start;
  1341.   if (line_ptr < limit && *line_ptr == '\\')
  1342.     {
  1343.       if (edscript)
  1344.     fprintf (stderr, "%s:", program_name);
  1345.       else
  1346.     --*set_length;
  1347.       line_ptr++;
  1348.       do
  1349.     {
  1350.       if (edscript)
  1351.         putc (*line_ptr, stderr);
  1352.     }
  1353.       while (*line_ptr++ != '\n');
  1354.     }
  1355.  
  1356.   return line_ptr;
  1357. }
  1358.  
  1359. /*
  1360.  * This routine outputs a three way diff passed as a list of
  1361.  * diff3_block's.
  1362.  * The argument MAPPING is indexed by external file number (in the
  1363.  * argument list) and contains the internal file number (from the
  1364.  * diff passed).  This is important because the user expects his
  1365.  * outputs in terms of the argument list number, and the diff passed
  1366.  * may have been done slightly differently (if the last argument
  1367.  * was "-", for example).
  1368.  * REV_MAPPING is the inverse of MAPPING.
  1369.  */
  1370. static void
  1371. output_diff3 (FILE *outputfile, struct diff3_block *diff,
  1372.           int const mapping[3], int const rev_mapping[3])
  1373. {
  1374.   int i;
  1375.   int oddoneout = 0;
  1376.   char *cp;
  1377.   struct diff3_block *ptr;
  1378.   lin line;
  1379.   size_t length;
  1380.   int dontprint = 0;
  1381.   static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
  1382.   char const *line_prefix = initial_tab ? "\t" : "  ";
  1383.  
  1384.   for (ptr = diff; ptr; ptr = D_NEXT (ptr))
  1385.     {
  1386.       char x[2];
  1387.  
  1388.       switch (ptr->correspond)
  1389.     {
  1390.     case DIFF_ALL:
  1391.       x[0] = 0;
  1392.       dontprint = 3;    /* Print them all */
  1393.       oddoneout = 3;    /* Nobody's odder than anyone else */
  1394.       break;
  1395.     case DIFF_1ST:
  1396.     case DIFF_2ND:
  1397.     case DIFF_3RD:
  1398.       oddoneout = rev_mapping[ptr->correspond - DIFF_1ST];
  1399.  
  1400.       x[0] = oddoneout + '1';
  1401.       x[1] = 0;
  1402.       dontprint = oddoneout == 0;
  1403.       break;
  1404.     default:
  1405.       fatal ("internal error: invalid diff type passed to output");
  1406.     }
  1407.       fprintf (outputfile, "====%s\n", x);
  1408.  
  1409.       /* Go 0, 2, 1 if the first and third outputs are equivalent.  */
  1410.       for (i = 0; i < 3;
  1411.        i = (oddoneout == 1 ? skew_increment[i] : i + 1))
  1412.     {
  1413.       int realfile = mapping[i];
  1414.       lin lowt = D_LOWLINE (ptr, realfile);
  1415.       lin hight = D_HIGHLINE (ptr, realfile);
  1416.       long llowt = lowt;
  1417.       long lhight = hight;
  1418.  
  1419.       fprintf (outputfile, "%d:", i + 1);
  1420.       switch (lowt - hight)
  1421.         {
  1422.         case 1:
  1423.           fprintf (outputfile, "%lda\n", llowt - 1);
  1424.           break;
  1425.         case 0:
  1426.           fprintf (outputfile, "%ldc\n", llowt);
  1427.           break;
  1428.         default:
  1429.           fprintf (outputfile, "%ld,%ldc\n", llowt, lhight);
  1430.           break;
  1431.         }
  1432.  
  1433.       if (i == dontprint) continue;
  1434.  
  1435.       if (lowt <= hight)
  1436.         {
  1437.           line = 0;
  1438.           do
  1439.         {
  1440.           fprintf (outputfile, line_prefix);
  1441.           cp = D_RELNUM (ptr, realfile, line);
  1442.           length = D_RELLEN (ptr, realfile, line);
  1443.           fwrite (cp, sizeof (char), length, outputfile);
  1444.         }
  1445.           while (++line < hight - lowt + 1);
  1446.           if (cp[length - 1] != '\n')
  1447.         fprintf (outputfile, "\n\\ %s\n",
  1448.              _("No newline at end of file"));
  1449.         }
  1450.     }
  1451.     }
  1452. }
  1453.  
  1454.  
  1455. /*
  1456.  * Output to OUTPUTFILE the lines of B taken from FILENUM.
  1457.  * Double any initial '.'s; yield nonzero if any initial '.'s were doubled.
  1458.  */
  1459. static bool
  1460. dotlines (FILE *outputfile, struct diff3_block *b, int filenum)
  1461. {
  1462.   lin i;
  1463.   bool leading_dot = 0;
  1464.  
  1465.   for (i = 0;
  1466.        i < D_NUMLINES (b, filenum);
  1467.        i++)
  1468.     {
  1469.       char *line = D_RELNUM (b, filenum, i);
  1470.       if (line[0] == '.')
  1471.     {
  1472.       leading_dot = 1;
  1473.       fprintf (outputfile, ".");
  1474.     }
  1475.       fwrite (line, sizeof (char),
  1476.           D_RELLEN (b, filenum, i), outputfile);
  1477.     }
  1478.  
  1479.   return leading_dot;
  1480. }
  1481.  
  1482. /*
  1483.  * Output to OUTPUTFILE a '.' line.  If LEADING_DOT is nonzero,
  1484.  * also output a command that removes initial '.'s
  1485.  * starting with line START and continuing for NUM lines.
  1486.  * (START is long, not lin, for convenience with printf %ld formats.)
  1487.  */
  1488. static void
  1489. undotlines (FILE *outputfile, bool leading_dot, long start, lin num)
  1490. {
  1491.   fprintf (outputfile, ".\n");
  1492.   if (leading_dot)
  1493.     {
  1494.       if (num == 1)
  1495.     fprintf (outputfile, "%lds/^\\.//\n", start);
  1496.       else
  1497.     fprintf (outputfile, "%ld,%lds/^\\.//\n", start, start + num - 1);
  1498.     }
  1499. }
  1500.  
  1501. #ifdef __riscos
  1502. /* Get a file's type.  */
  1503. static int
  1504. gettype (const char *filename)
  1505. {
  1506.   struct stat st;
  1507.   return stat (filename, &st) < 0 ? -1 : st.st_type;
  1508. }
  1509. #endif
  1510.  
  1511. /*
  1512.  * This routine outputs a diff3 set of blocks as an ed script.  This
  1513.  * script applies the changes between file's 2 & 3 to file 1.  It
  1514.  * takes the precise format of the ed script to be output from global
  1515.  * variables set during options processing.  Note that it does
  1516.  * destructive things to the set of diff3 blocks it is passed; it
  1517.  * reverses their order (this gets around the problems involved with
  1518.  * changing line numbers in an ed script).
  1519.  *
  1520.  * Note that this routine has the same problem of mapping as the last
  1521.  * one did; the variable MAPPING maps from file number according to
  1522.  * the argument list to file number according to the diff passed.  All
  1523.  * files listed below are in terms of the argument list.
  1524.  * REV_MAPPING is the inverse of MAPPING.
  1525.  *
  1526.  * The arguments FILE0, FILE1 and FILE2 are the strings to print
  1527.  * as the names of the three files.  These may be the actual names,
  1528.  * or may be the arguments specified with -L.
  1529.  *
  1530.  * Returns 1 if conflicts were found.
  1531.  */
  1532.  
  1533. static bool
  1534. output_diff3_edscript (FILE *outputfile, struct diff3_block *diff,
  1535.                int const mapping[3], int const rev_mapping[3],
  1536.                char const *file0, char const *file1, char const *file2)
  1537. {
  1538.   bool leading_dot;
  1539.   bool conflicts_found = 0, conflict;
  1540.   struct diff3_block *b;
  1541.  
  1542.   for (b = reverse_diff3_blocklist (diff); b; b = b->next)
  1543.     {
  1544.       /* Must do mapping correctly.  */
  1545.       enum diff_type type
  1546.     = (b->correspond == DIFF_ALL
  1547.        ? DIFF_ALL
  1548.        : DIFF_1ST + rev_mapping[b->correspond - DIFF_1ST]);
  1549.  
  1550.       long low0, high0;
  1551.  
  1552.       /* If we aren't supposed to do this output block, skip it.  */
  1553.       switch (type)
  1554.     {
  1555.     default: continue;
  1556.     case DIFF_2ND: if (!show_2nd) continue; conflict = 1; break;
  1557.     case DIFF_3RD: if (overlap_only) continue; conflict = 0; break;
  1558.     case DIFF_ALL: if (simple_only) continue; conflict = flagging; break;
  1559.     }
  1560.  
  1561.       low0 = D_LOWLINE (b, mapping[FILE0]);
  1562.       high0 = D_HIGHLINE (b, mapping[FILE0]);
  1563.  
  1564.       if (conflict)
  1565.     {
  1566. #ifdef __riscos
  1567.       int ftype;
  1568. #endif
  1569.       conflicts_found = 1;
  1570.  
  1571.  
  1572.       /* Mark end of conflict.  */
  1573.  
  1574.       fprintf (outputfile, "%lda\n", high0);
  1575.       leading_dot = 0;
  1576.       if (type == DIFF_ALL)
  1577.         {
  1578.           if (show_2nd)
  1579.         {
  1580.           /* Append lines from FILE1.  */
  1581. #ifdef __riscos
  1582.           if (append_filetypes && (ftype = gettype (file1)) != -1)
  1583.             fprintf (outputfile, "||||||| %s,%03x\n",
  1584.                  ro_tounix (file1, extension_names), ftype);
  1585.           else
  1586.             fprintf (outputfile, "||||||| %s\n",
  1587.                  ro_tounix (file1, extension_names));
  1588. #else
  1589.           fprintf (outputfile, "||||||| %s\n", file1);
  1590. #endif
  1591.           leading_dot = dotlines (outputfile, b, mapping[FILE1]);
  1592.         }
  1593.           /* Append lines from FILE2.  */
  1594.           fprintf (outputfile, "=======\n");
  1595.           leading_dot |= dotlines (outputfile, b, mapping[FILE2]);
  1596.         }
  1597. #ifdef __riscos
  1598.       if (append_filetypes && (ftype = gettype (file2)) != -1)
  1599.         fprintf (outputfile, ">>>>>>> %s,%03x\n",
  1600.              ro_tounix (file2, extension_names), ftype);
  1601.       else
  1602.         fprintf (outputfile, ">>>>>>> %s\n",
  1603.              ro_tounix (file2, extension_names));
  1604. #else
  1605.       fprintf (outputfile, ">>>>>>> %s\n", file2);
  1606. #endif
  1607.       undotlines (outputfile, leading_dot, high0 + 2,
  1608.               (D_NUMLINES (b, mapping[FILE1])
  1609.                + D_NUMLINES (b, mapping[FILE2]) + 1));
  1610.  
  1611.  
  1612.       /* Mark start of conflict.  */
  1613.  
  1614. #ifdef __riscos
  1615.       if (append_filetypes
  1616.           && (ftype = gettype (type == DIFF_ALL ? file0 : file1)) != -1)
  1617.         fprintf (outputfile, "%lda\n<<<<<<< %s,%03x\n", low0 - 1,
  1618.              ro_tounix (type == DIFF_ALL ? file0 : file1,
  1619.                 extension_names),
  1620.              ftype);
  1621.       else
  1622.         fprintf (outputfile, "%lda\n<<<<<<< %s\n", low0 - 1,
  1623.              ro_tounix (type == DIFF_ALL ? file0 : file1,
  1624.                 extension_names));
  1625. #else
  1626.       fprintf (outputfile, "%lda\n<<<<<<< %s\n", low0 - 1,
  1627.            type == DIFF_ALL ? file0 : file1);
  1628. #endif
  1629.       leading_dot = 0;
  1630.       if (type == DIFF_2ND)
  1631.         {
  1632.           /* Prepend lines from FILE1.  */
  1633.           leading_dot = dotlines (outputfile, b, mapping[FILE1]);
  1634.           fprintf (outputfile, "=======\n");
  1635.         }
  1636.       undotlines (outputfile, leading_dot, low0 + 1,
  1637.               D_NUMLINES (b, mapping[FILE1]));
  1638.     }
  1639.       else if (D_NUMLINES (b, mapping[FILE2]) == 0)
  1640.     /* Write out a delete */
  1641.     {
  1642.       if (low0 == high0)
  1643.         fprintf (outputfile, "%ldd\n", low0);
  1644.       else
  1645.         fprintf (outputfile, "%ld,%ldd\n", low0, high0);
  1646.     }
  1647.       else
  1648.     /* Write out an add or change */
  1649.     {
  1650.       switch (high0 - low0)
  1651.         {
  1652.         case -1:
  1653.           fprintf (outputfile, "%lda\n", high0);
  1654.           break;
  1655.         case 0:
  1656.           fprintf (outputfile, "%ldc\n", high0);
  1657.           break;
  1658.         default:
  1659.           fprintf (outputfile, "%ld,%ldc\n", low0, high0);
  1660.           break;
  1661.         }
  1662.  
  1663.       undotlines (outputfile, dotlines (outputfile, b, mapping[FILE2]),
  1664.               low0, D_NUMLINES (b, mapping[FILE2]));
  1665.     }
  1666.     }
  1667.   if (finalwrite) fprintf (outputfile, "w\nq\n");
  1668.   return conflicts_found;
  1669. }
  1670.  
  1671. /*
  1672.  * Read from INFILE and output to OUTPUTFILE a set of diff3_ blocks DIFF
  1673.  * as a merged file.  This acts like 'ed file0 <[output_diff3_edscript]',
  1674.  * except that it works even for binary data or incomplete lines.
  1675.  *
  1676.  * As before, MAPPING maps from arg list file number to diff file number,
  1677.  * REV_MAPPING is its inverse,
  1678.  * and FILE0, FILE1, and FILE2 are the names of the files.
  1679.  *
  1680.  * Returns 1 if conflicts were found.
  1681.  */
  1682.  
  1683. static bool
  1684. output_diff3_merge (FILE *infile, FILE *outputfile, struct diff3_block *diff,
  1685.             int const mapping[3], int const rev_mapping[3],
  1686.             char const *file0, char const *file1, char const *file2)
  1687. {
  1688.   int c;
  1689.   lin i;
  1690.   bool conflicts_found = 0, conflict;
  1691.   struct diff3_block *b;
  1692.   lin linesread = 0;
  1693.  
  1694.   for (b = diff; b; b = b->next)
  1695.     {
  1696.       /* Must do mapping correctly.  */
  1697.       enum diff_type type
  1698.     = ((b->correspond == DIFF_ALL)
  1699.        ? DIFF_ALL
  1700.        : DIFF_1ST + rev_mapping[b->correspond - DIFF_1ST]);
  1701. #ifdef __riscos
  1702.       int ftype;
  1703.       char const *format_2nd = "<<<<<<< %s\n";
  1704.       char const *format_2nd_ft = "<<<<<<< %s,%03\n";
  1705. #else
  1706.       char const *format_2nd = "<<<<<<< %s\n";
  1707. #endif
  1708.  
  1709.       /* If we aren't supposed to do this output block, skip it.  */
  1710.       switch (type)
  1711.     {
  1712.     default: continue;
  1713.     case DIFF_2ND: if (!show_2nd) continue; conflict = 1; break;
  1714.     case DIFF_3RD: if (overlap_only) continue; conflict = 0; break;
  1715.     case DIFF_ALL: if (simple_only) continue; conflict = flagging;
  1716.       format_2nd = "||||||| %s\n";
  1717. #ifdef __riscos
  1718.       format_2nd_ft = "||||||| %s,%03x\n";
  1719. #endif
  1720.       break;
  1721.     }
  1722.  
  1723.       /* Copy I lines from file 0.  */
  1724.       i = D_LOWLINE (b, FILE0) - linesread - 1;
  1725.       linesread += i;
  1726.       while (0 <= --i)
  1727.     do
  1728.       {
  1729.         c = getc (infile);
  1730.         if (c == EOF)
  1731.           {
  1732.         if (ferror (infile))
  1733.           perror_with_exit (_("read failed"));
  1734.         else if (feof (infile))
  1735.           fatal ("input file shrank");
  1736.           }
  1737.         putc (c, outputfile);
  1738.       }
  1739.     while (c != '\n');
  1740.  
  1741.       if (conflict)
  1742.     {
  1743.       conflicts_found = 1;
  1744.  
  1745.       if (type == DIFF_ALL)
  1746.         {
  1747.           /* Put in lines from FILE0 with bracket.  */
  1748. #ifdef __riscos
  1749.           if (append_filetypes && (ftype = gettype (file0)) != -1)
  1750.         fprintf (outputfile, "<<<<<<< %s,%03x\n",
  1751.              ro_tounix (file0, extension_names), ftype);
  1752.           else
  1753.         fprintf (outputfile, "<<<<<<< %s\n",
  1754.              ro_tounix (file0, extension_names));
  1755. #else
  1756.           fprintf (outputfile, "<<<<<<< %s\n", file0);
  1757. #endif
  1758.           for (i = 0;
  1759.            i < D_NUMLINES (b, mapping[FILE0]);
  1760.            i++)
  1761.         fwrite (D_RELNUM (b, mapping[FILE0], i), sizeof (char),
  1762.             D_RELLEN (b, mapping[FILE0], i), outputfile);
  1763.         }
  1764.  
  1765.       if (show_2nd)
  1766.         {
  1767.           /* Put in lines from FILE1 with bracket.  */
  1768. #ifdef __riscos
  1769.           if (append_filetypes && (ftype = gettype (file1)) != -1)
  1770.         fprintf (outputfile, format_2nd_ft,
  1771.              ro_tounix (file1, extension_names), ftype);
  1772.           else
  1773.         fprintf (outputfile, format_2nd,
  1774.              ro_tounix (file1, extension_names));
  1775. #else
  1776.           fprintf (outputfile, format_2nd, file1);
  1777. #endif
  1778.           for (i = 0;
  1779.            i < D_NUMLINES (b, mapping[FILE1]);
  1780.            i++)
  1781.         fwrite (D_RELNUM (b, mapping[FILE1], i), sizeof (char),
  1782.             D_RELLEN (b, mapping[FILE1], i), outputfile);
  1783.         }
  1784.  
  1785.       fprintf (outputfile, "=======\n");
  1786.     }
  1787.  
  1788.       /* Put in lines from FILE2.  */
  1789.       for (i = 0;
  1790.        i < D_NUMLINES (b, mapping[FILE2]);
  1791.        i++)
  1792.     fwrite (D_RELNUM (b, mapping[FILE2], i), sizeof (char),
  1793.         D_RELLEN (b, mapping[FILE2], i), outputfile);
  1794.  
  1795.       if (conflict)
  1796. #ifdef __riscos
  1797.     {
  1798.       if (append_filetypes && (ftype = gettype (file2)) != -1)
  1799.         fprintf (outputfile, ">>>>>>> %s,%03x\n",
  1800.              ro_tounix (file2, extension_names), ftype);
  1801.       else
  1802.         fprintf (outputfile, "<<<<<<< %s\n",
  1803.              ro_tounix (file2, extension_names));
  1804.     }
  1805. #else
  1806.     fprintf (outputfile, ">>>>>>> %s\n", file2);
  1807. #endif
  1808.  
  1809.       /* Skip I lines in file 0.  */
  1810.       i = D_NUMLINES (b, FILE0);
  1811.       linesread += i;
  1812.       while (0 <= --i)
  1813.     while ((c = getc (infile)) != '\n')
  1814.       if (c == EOF)
  1815.         {
  1816.           if (ferror (infile))
  1817.         perror_with_exit (_("read failed"));
  1818.           else if (feof (infile))
  1819.         {
  1820.           if (i || b->next)
  1821.             fatal ("input file shrank");
  1822.           return conflicts_found;
  1823.         }
  1824.         }
  1825.     }
  1826.   /* Copy rest of common file.  */
  1827.   while ((c = getc (infile)) != EOF || !(ferror (infile) | feof (infile)))
  1828.     putc (c, outputfile);
  1829.   return conflicts_found;
  1830. }
  1831.  
  1832. /*
  1833.  * Reverse the order of the list of diff3 blocks.
  1834.  */
  1835. static struct diff3_block *
  1836. reverse_diff3_blocklist (struct diff3_block *diff)
  1837. {
  1838.   register struct diff3_block *tmp, *next, *prev;
  1839.  
  1840.   for (tmp = diff, prev = 0;  tmp;  tmp = next)
  1841.     {
  1842.       next = tmp->next;
  1843.       tmp->next = prev;
  1844.       prev = tmp;
  1845.     }
  1846.  
  1847.   return prev;
  1848. }
  1849.  
  1850. static void
  1851. fatal (char const *msgid)
  1852. {
  1853.   error (EXIT_TROUBLE, 0, "%s", _(msgid));
  1854.   abort ();
  1855. }
  1856.  
  1857. static void
  1858. perror_with_exit (char const *string)
  1859. {
  1860.   error (EXIT_TROUBLE, errno, "%s", string);
  1861.   abort ();
  1862. }
  1863.